package com.fan.configService.service;

import com.fan.configService.config.StaticConstant;
import com.fan.configService.exception.QhException;
import com.fan.configService.exception.QhUserErrors;
import com.fan.configService.shiro.JwtHelper;
import com.fan.configService.shiro.JwtToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author huangfan
 * @date 2016年9月28日
 */

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermission("get");
        return simpleAuthorizationInfo;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;
        boolean b = JwtHelper.validToken(jwtToken.getCredentials().toString(), JwtHelper.SIGNATURE);
        if (!b) {
            throw new QhException(QhUserErrors.TOKEN_VERIFY_NO_PASSED);
        }
        Map<String, Object> payloadMap = JwtHelper.getPayloadMap(jwtToken.getCredentials().toString());
        Object userId = payloadMap.get(StaticConstant.USERID);
        SimpleHash credentials = new SimpleHash("MD5", "huangfan");
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userId, jwtToken.getCredentials().toString(), this.getName());
        return simpleAuthenticationInfo;
    }
}
